import { login, getInfo, getDetailInfo } from '@/api/user'

import { getToken, setToken, removeToken } from '@/utils/auth'

// import { resetRouter } from '@/router'

const getDefaultState = () => {
    return {
        //优先从缓存中读取原有的token
        token: getToken(),
        name: '',
        avatar: '',
        //用户信息
        userInfo: null,
    }
}

const state = getDefaultState()

const mutations = {
    RESET_STATE: (state) => {
        Object.assign(state, getDefaultState())
    },
    //vuex中的token
    SET_TOKEN: (state, token) => {
        state.token = token
    },
    SET_NAME: (state, name) => {
        state.name = name
    },
    SET_AVATAR: (state, avatar) => {
        state.avatar = avatar
    },
    //清除用户信息
    clearInfo(state) {
        state.userInfo = null
    },

    //退出登录清除用户信息
    clearInfo(state) {
        state.userInfo = null
    },
    //获取用户信息  payload为形参 
    updateUserInfo(state, payload) {
        // 初始化用户信息
        if (state.userInfo) {
            // 原来有值（合并两个对象的所有属性到一块）
            state.userInfo = {
                ...state.userInfo,
                ...payload
            }
        } else {
            // 第一次给他初始化
            state.userInfo = payload
        }
    }
}

const actions = {
    // 退出登录4步骤



    //4.跳转到登陆页面
    logout({ commit }) {
        //1.清除vuex中的用户信息
        commit('SET_TOKEN', '')
            //2.清除缓存中的用户信息
        commit('clearInfo')
            //3.删除缓存中的token
        removeToken()
    },

    // user login  action的返回值是Promise实例对象
    async login({ commit }, userInfo) {
        const { username, password } = userInfo
        const ret = await login({
            mobile: username.trim(),
            password: password
        })
        if (ret.code === 10000) {
            // 登录成功
            commit('SET_TOKEN', ret.data)
                // 缓存token 存到
            setToken(ret.data)
            return Promise.resolve(true)
        } else {
            // 登录失败
            return Promise.reject(false)
        }
    },
    // get user info
    async getInfo({ commit, state }) {
        const res = await getInfo()
        commit('updateUserInfo', res.data)
    },
    //获取用户详细信息
    async getDetailInfo(store, id) {
        const req = await getDetailInfo(id)
        store.commit('updateUserInfo', req.data)
            // console.log(5555);
    },





    // remove token
    resetToken({ commit }) {
        return new Promise(resolve => {
            removeToken() // must remove  token  first
            commit('RESET_STATE')
            resolve()
        })
    }
}

export default {
    //命名空间 
    namespaced: true,
    state,
    mutations,
    actions
}